package com.levy.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.levy.domain.User;

/**
 * 用户数据访问对象
 *
 * @author liwei515
 */
@Repository  // 通过Spring注解定义一个DAO
public class UserDao {

  private JdbcTemplate jdbcTemplate;

  private final static String MATCH_COUNT_SQL = " SELECT count(*) FROM " + " t_user WHERE user_name = ? and password = ? ";

  private final static String UPDATE_LOGIN_INFO_SQL = " UPDATE t_user SET " + "last_visit = ?, last_ip = ?, credits = ? WHERE user_id = ? ";

  /**
   * set方法注入JdbcTemplate的Bean
   *
   * @param jdbcTemplate Spring对JDBC封装的模板
   */
  @Autowired
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  /**
   * 根据用户名和密码获取匹配的用户数
   *
   * @param userName 用户名
   * @param password 密码
   * @return 用户人数
   */
  public int getMatchCount(String userName, String password) {
    return jdbcTemplate.queryForObject(MATCH_COUNT_SQL, new Object[]{ userName, password}, Integer.class);
  }

  /**
   * 根据用户名获取User对象
   *
   * @param userName 用户名
   * @return 用户对象实体类
   */
  public User findUserByUserName(final String userName) {
    String sqlStr = " SELECT user_id, user_name, credits " + " FROM t_user WHERE user_name = ? ";
    final User user = new User();
    jdbcTemplate.query(sqlStr, new Object[]{userName}, new RowCallbackHandler() {
      @Override
      public void processRow(ResultSet resultSet) throws SQLException {
        user.setUserId(resultSet.getInt("user_id"));
        user.setUserName(userName);
        user.setCredits(resultSet.getInt("credits"));
      }
    });
    return user;
  }

  /**
   * 更新用户积分、最后登录IP及最后登陆时间
   *
   * @param user 传入的用户实体类对象
   */
  public void updateLoginInfo(User user) {
    jdbcTemplate.update(UPDATE_LOGIN_INFO_SQL, new Object[] {user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()});
  }
}
